package com.example.AiLangLearn.personatetts;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.AiLangLearn.R;
import com.example.AiLangLearn.adapter.SpinnerAdapter;
import com.example.AiLangLearn.utils.AudioTrackManager;
import com.example.AiLangLearn.utils.FileUtils;
import com.iflytek.sparkchain.core.tts.PersonateTTS;
import com.iflytek.sparkchain.core.tts.TTS;
import com.iflytek.sparkchain.core.tts.TTSCallbacks;
import com.iflytek.sparkchain.plugins.mail.Mail;

import java.io.File;


public class PersonateTTSActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener,
        AdapterView.OnItemSelectedListener,View.OnClickListener{
    public static final String WORK_DIR = "/sdcard/iflytek/personatetts";
    private final String TAG = "AEE";
    private TextView btn_Test_start,btn_Test_stop;
    private String text = "好好学习，天天向上";
    private String texts[] = {
            "技术支持跑的快，全靠大佬们带。受着老板们和研发大佬的熏陶，技术支持也是不会掉队的。",
            "2024年9月26日，星期四，小明在这一天开启了一段充满惊喜的冒险之旅。",
            "床前明月光，疑似地上霜。",
            "阳光透过斑驳的树叶洒在街道上。微风轻拂，似在诉说着岁月的故事。心，在这宁静的时光里，渐渐沉醉。"
    };

    private PersonateTTS personateTTS;
    private int AEE_TTS_END = 1001;

    private int speed = 50;
    private int pitch = 50;
    private int volume = 50;

    private Spinner vncSpinner;

    private SeekBar mPitchSeekBar,mSpeedSeekBar,mVolumeSeekBar;

    private TextView mPitchTxt,mSpeedTxt,mVolumeTxt;

    private EditText mEd_Text;

    private String outPcmName = null;

    private ProgressDialog progressDialog;

    private PersonateTTSParams mPersonateTTSParams = new PersonateTTSParams();
    private void initView(){
        btn_Test_start = findViewById(R.id.personatetts_play_btn);
        btn_Test_stop = findViewById(R.id.personatetts_stop_btn);
        btn_Test_start.setOnClickListener(this);
        btn_Test_stop.setOnClickListener(this);
        vncSpinner = findViewById(R.id.personatetts_vcn_spinner);
        SpinnerAdapter vncAdapter = new SpinnerAdapter(this, PersonateTTSParams.getVCN());
        vncSpinner.setAdapter(vncAdapter);
        vncSpinner.setOnItemSelectedListener(this);

        mPitchSeekBar = findViewById(R.id.personatetts_pitch_seekbar);
        mSpeedSeekBar = findViewById(R.id.personatetts_speed_seekbar);
        mVolumeSeekBar = findViewById(R.id.personatetts_volume_seekbar);
        mPitchSeekBar.setOnSeekBarChangeListener(this);
        mSpeedSeekBar.setOnSeekBarChangeListener(this);
        mVolumeSeekBar.setOnSeekBarChangeListener(this);

        mPitchTxt = findViewById(R.id.personatetts_pitch_txt);
        mSpeedTxt = findViewById(R.id.personatetts_speed_txt);
        mVolumeTxt = findViewById(R.id.personatetts_volume_txt);

        mEd_Text = findViewById(R.id.personatetts_input);
    }


    TTSCallbacks mTTSCallback = new TTSCallbacks() {

        @Override
        public void onResult(TTS.TTSResult result, Object o) {
            Log.d(TAG, "onResult:seq:" + result.getSeq() + ",status:" + result.getStatus());
            byte[] audio = result.getData();
            if(audio!=null){
                FileUtils.writeFile(outPcmName, audio);
            }else{
                Log.d(TAG,"audio is null");
            }

            if(result.getStatus() == 2){
                handler.sendEmptyMessage(AEE_TTS_END);
            }

        }

        @Override
        public void onError(TTS.TTSError ttsError, Object o) {
            Log.d(TAG, "onError:errCode:" + ttsError.getCode() + ",errMsg:" + ttsError.getErrMsg());
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    };

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == AEE_TTS_END) {
                Log.d(TAG,"read media play");
                AudioTrackManager.getInstance().setSampleRate(AudioTrackManager.sampleRateType.SAMPLE_RATE_16k);//播报前先设置采样率
                Log.d(TAG,"read media play:"+outPcmName);
                AudioTrackManager.getInstance().startPlay(outPcmName);
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
            return false;
        }
    });

    private void initDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("合成中，请稍后...");
    }

    private void start(){
        Log.d(TAG,"start-->");
        Log.d(TAG,"vcn = " + mPersonateTTSParams.vcn);
        Log.d(TAG,"pitch = " + mPersonateTTSParams.pitch);
        Log.d(TAG,"speed = " + mPersonateTTSParams.speed);
        Log.d(TAG,"volume = " + mPersonateTTSParams.volume);
        text = mEd_Text.getText().toString();
        Log.d(TAG,"text = " + text);
        progressDialog.show();
        AudioTrackManager.getInstance().stopPlay();
        personateTTS = new PersonateTTS(mPersonateTTSParams.vcn);
        personateTTS.speed(mPersonateTTSParams.speed);
        personateTTS.pitch(mPersonateTTSParams.pitch);
        personateTTS.volume(mPersonateTTSParams.volume);
        personateTTS.sparkAssist(true);
        personateTTS.oralLevel("high");
        personateTTS.registerCallbacks(mTTSCallback);
        personateTTS.aRun(text);
    }

    private void startflow(){
        Log.d(TAG,"startflow-->");
        Log.d(TAG,"vcn = " + mPersonateTTSParams.vcn);
        Log.d(TAG,"pitch = " + mPersonateTTSParams.pitch);
        Log.d(TAG,"speed = " + mPersonateTTSParams.speed);
        Log.d(TAG,"volume = " + mPersonateTTSParams.volume);
        progressDialog.show();
        AudioTrackManager.getInstance().stopPlay();
        personateTTS = new PersonateTTS(mPersonateTTSParams.vcn);
        personateTTS.speed(mPersonateTTSParams.speed);
        personateTTS.pitch(mPersonateTTSParams.pitch);
        personateTTS.volume(mPersonateTTSParams.volume);
        personateTTS.sparkAssist(true);
        personateTTS.oralLevel("high");
        personateTTS.registerCallbacks(mTTSCallback);
        int status = 0;
        for(int i = 0;i<texts.length;i++){
            if(i == 0){
                status = 0;
            }else if(i == texts.length-1){
                status = 2;
            }else{
                status = 1;
            }
            Log.d(TAG,"status = " + status);
            personateTTS.aRun(texts[i],status);
        }

    }


    private void stop(){
        if(personateTTS!=null) {
            AudioTrackManager.getInstance().stopPlay();
            personateTTS.stop();
            personateTTS = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personatetts);
        Window window = this.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        initView();
        initDialog();
        createWorkDir();
    }


    private void createWorkDir(){
        File folder = new File(WORK_DIR);
        if (!folder.exists()) {
            boolean success = folder.mkdirs();
            if (success) {
                // 文件夹创建成功
            } else {
                // 文件夹创建失败
                Toast.makeText(getApplicationContext(),"超拟人音频存放路径创建失败，请手动创建/sdcard/iflytek/personatetts",Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.personatetts_play_btn:
                if(mEd_Text.getText().toString().length() > 0) {
                    outPcmName = WORK_DIR + "/output_" + mPersonateTTSParams.vcn + System.currentTimeMillis() + ".pcm";
                    start();
                }else{
                    Toast.makeText(this,"内容不可为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.personatetts_stop_btn:
                stop();
                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.personatetts_vcn_spinner:
                mPersonateTTSParams.vcn = PersonateTTSParams.getVCN().get(position).value;
                break;
            default:
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.personatetts_pitch_seekbar:
                mPersonateTTSParams.pitch = progress;
                mPitchTxt.setText(String.valueOf(progress));
                break;
            case R.id.personatetts_speed_seekbar:
                mPersonateTTSParams.speed = progress;
                mSpeedTxt.setText(String.valueOf(progress));
                break;
            case R.id.personatetts_volume_seekbar:
                mPersonateTTSParams.volume = progress;
                mVolumeTxt.setText(String.valueOf(progress));
                break;
            default:
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}